package com.cloudbroker.bcs.common.config;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

/**
 * Created by lvjx on 2015/6/23.
 * @desc 从zk中读取数据,并将该数据存储为文件
 * */
@Ignore
public class ZkFileCreater {


    private  CuratorFramework cf = null;


    @Before
    public  void before(){
        cf = CuratorFrameworkFactory.builder().sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .connectString("127.0.0.1")
                .build();
        cf.start();
    }

    /***
     * 从zk中读取配置信息并保存为xml文件
     * @throws Exception
     */
    @Test
    public void readDataFromZk() throws Exception {
        String node = "/cloud";

        cf.getData().forPath(node);
        Map<String,String> map = new LinkedHashMap<>();
        Stack<String> nodeStack = new Stack<String>();
        nodeStack.add(node);
        while (!nodeStack.isEmpty()) {
            node = nodeStack.pop();
            map.put(node,new String(cf.getData().forPath(node),"utf-8"));
            //获得节点的子节点，对于二叉树就是获得节点的左子结点和右子节点
            List<String> children =cf.getChildren().forPath(node);
            if (children != null && !children.isEmpty()) {
                for (String child : children) {
                    nodeStack.push(node+"/"+child);
                }
            }
        }
        FileOutputStream baos = new FileOutputStream(new File("f:/lvjx.xml"));
        XMLEncoder xmlEncoder = new XMLEncoder(baos);
        xmlEncoder.writeObject(map);
        xmlEncoder.close();

    }


    /***
     * 从zk中读取配置信息并保存为xml文件
     * @throws Exception
     */
    @Test
    public void writeDataFromXmltoZk() throws Exception{
        String zk_root_node = "/cloud_backup";
        FileInputStream fis = new FileInputStream(new File("f:/lvjx.xml"));
        XMLDecoder xmlDecoder = new XMLDecoder(fis);
        Map<String,String> map = (Map<String, String>) xmlDecoder.readObject();

        if(cf.checkExists().forPath(zk_root_node)!=null){
            cf.delete().forPath(zk_root_node);
        }
        cf.create().creatingParentsIfNeeded().forPath(zk_root_node);

        for (String s : map.keySet()) {
            if(s.indexOf("/",1)!=-1){
                String new_node = zk_root_node+s.substring(s.indexOf("/",1));
                cf.create().creatingParentsIfNeeded().forPath(new_node);
                cf.setData().forPath(new_node,map.get(s).getBytes("utf-8"));
            }
        }
    }

}
